package com.zoiz.dbutils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

import org.apache.commons.dbutils.DbUtils;

import com.zoiz.plus.extend.TypeInferFactory;
import com.zoiz.util.Configurations;

public class ThreadHolder {
	private static ThreadLocal<ThreadHolder> holder = new ThreadLocal<ThreadHolder>(){
		@Override
		protected ThreadHolder initialValue() {
			return null;
		}
	};
	private Connection connection;
	private Map<String, Object> _model = TypeInferFactory.newHashMap();

	public Map<String, Object> get_model() {
		return _model;
	}

	public static ThreadHolder getHolder() {
		if (holder.get() == null) {
			holder.set(new ThreadHolder());
		}
		return holder.get();
	}

	public void set_model(Map<String, Object> _model) {
		this._model = _model;
	}

	public static Connection getCurrentConnection() {
		return getHolder().getConnection();
	}

	public void closeConnection(){
		if(connection!=null){
			try {
				connection.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public Connection getConnection() {
		if (connection == null) {
			setConnection(Configurations.getConnection());
		}
		return connection;
	}

	public void setConnection(Connection connection) {
		this.connection = connection;
	}

	public static void removeCurrentConnection() {
		DbUtils.closeQuietly(getCurrentConnection());
	}
	public static void removeThreadHolder(){
		holder.remove();
	}
}
